<!--
 @description 经销商业务变更-编辑
 @fileName Add.vue
 @author zengqiongying
 @created 2023-04-26 20:41:28
-->
<template>
  <div class="has-foot-pb">
    <Card>
      <DealerCell :detail="dealerData">
        <div style="margin-top: 8px" :class="{ 'color-org': typeCode === 'D', 'color-normal': typeCode === 'C' }">
          经销商门店{{ typeCode === 'C' ? '新增业务' : '取消业务' }}
        </div>
      </DealerCell>
    </Card>
    <Card>
      <FieldSelect
        v-model="formData.isOtherReceiveManagerKnow"
        title="是否需要其他业务客户经理接收知晓"
        :url="`/data-dict/app/v2/dictionary/BOOLEANS`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        required
      />
      <template v-if="[1, '1'].includes(formData.isOtherReceiveManagerKnow)">
        <Cell
          v-if="detail.officeCode && detail.customerCode"
          :modelValue="formData.receiveManagerName"
          title="接收客户经理"
          placeholder="选择客户经理"
          :required="['1', 1].includes(formData.isOtherReceiveManagerKnow)"
          @right="onSearchCustomerManager"
        />

        <template v-if="!!formData.receiveManagerCode">
          <Cell :modelValue="formData.receiveManagerCode" title="接收客户经理编码" readonly />
          <Cell :modelValue="formData.receiveManagerTypeName" title="接收客户经理类型" readonly />
          <Cell :modelValue="formData.receiveManagerTel" title="接收客户经理电话" readonly />
        </template>
      </template>
      <Cell title="提报意见" is-column custom :right="false">
        <qmp-field v-model="formData.submitAnOpinion" type="textarea" placeholder="输入内容" class="ctm-text-area" />
      </Cell>
    </Card>

    <Card :title="`选择${typeName}的店铺`" sub-title="点击编辑进入编辑店铺">
      <div class="shop-list">
        <div class="shop-checkbox" v-for="(item, i) in shopList" :key="i">
          <div class="check-status" :class="{ checked: item.isChange }"></div>
          <div class="shop-item has-pr">
            <div class="title">{{ item.name }}</div>
            <div class="address">{{ item.shopAddr }}</div>
            <div class="btn-edit" @click.stop="onEditShop(item)"></div>
          </div>
        </div>
      </div>
    </Card>
    <div class="ctm-content-foot">
      <div class="btn radius-larg ctm-btn-warning" @click="onSave('B')">提交</div>
      <div class="btn radius-larg ctm-btn-main" @click="onView">预览</div>
      <div class="btn radius-larg ctm-btn-main" @click="onSave('A')">保存</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance, nextTick, computed, watch, onActivated, onMounted } from 'vue'
  import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router'
  import { useStore } from 'vuex'
  import Card from '@/components/Card/index.vue'
  import Cell from '@/components/Cell/index.vue'
  import DealerCell from '@/components/DealerCell/index.vue'
  import FieldSelect from '@/components/FieldSelect/index.vue'
  import { detail, submitChange } from '@/apis/dealerMarketing/ShopChange'
  import { createSave } from '@/apis/ctmCustomerChange/index'
  import { initFormData } from '@/utils'

  const none: any[] = [undefined, null, '']
  interface anyObjectModle {
    [key: string]: any
  }
  export default {
    name: 'DealerShopChangeEdit',
    components: { Card, Cell, DealerCell, FieldSelect },
    setup() {
      const instance = getCurrentInstance()
      const { proxy }: any = instance
      const $store = useStore()
      const $router = useRouter()
      const $route = useRoute()
      const datas = reactive<anyObjectModle>({
        id: $route.query.id || '',
        dictParams: { query: { appCode: 'slm', domainCode: 'marketing' }, type: 0 },
        detail: {},
        formData: {
          code: '', //单据编号
          isOtherReceiveManagerKnow: '',
          receiveManagerCode: '', // 接收客户经理
          receiveManagerName: '',
          receiveManagerTel: '',
          receiveManagerTypeCode: '',
          receiveManagerTypeName: '',
          submitAnOpinion: ''
        }
      })

      onBeforeRouteLeave((to, from) => {
        const instanceName = instance?.type?.name
        const toName: any = to.name
        if (['DealerInfoShopChange', 'DealerShopChangeDetail'].includes(toName)) {
          $store.commit('routerKeep/removeCache', instanceName)
        } else {
          $store.commit('routerKeep/resetCache', instanceName)
        }
      })

      const setPageTitle = () => {
        if (!['C', 'D'].includes(datas.detail.type)) return
        proxy.$SimpleEvents.emit('routeMetaTitle', datas.detail.type === 'C' ? '新增业务编辑' : '取消业务编辑')
      }

      onActivated(() => {
        setPageTitle()
      })
      watch(
        () => datas.detail.type,
        () => {
          setPageTitle()
        }
      )

      // 单据类型
      const typeCode = computed(() => {
        return datas.detail?.type || 'C'
      })
      // 单据类型
      const typeName = computed(() => {
        return typeCode.value === 'C' ? '新增业务变更' : '取消业务变更'
      })

      const dealerData = computed(() => {
        const d = { ...datas.detail }
        return {
          code: d.customerCode || '',
          name: d.customerName || '',
          officeCode: d.officeCode || '',
          officeName: d.officeName || '',
          createBy: d.createBy || ''
        }
      })
      const shopList = computed(() => {
        return datas.detail?.shopBusinessDTOS || []
      })

      const getFormData = () => {
        const { formData }: any = datas
        let data: anyObjectModle = {
          ...formData
        }
        return data
      }

      const onSave = (schedule: string, callback: any) => {
        const data: anyObjectModle = getFormData()
        if (schedule === 'B') {
          if (none.includes(data.isOtherReceiveManagerKnow)) {
            proxy.$toast('请选择是否需要其他业务客户经理接收知晓')
            return
          }
          if ([1, '1'].includes(data.isOtherReceiveManagerKnow)) {
            if (none.includes(data.receiveManagerCode)) {
              proxy.$toast('请选择接收客户经理')
              return
            }
          }
          const flag = shopList.value.some((v: any) => v.isChange)
          if (!flag) {
            proxy.$toast(`选择${typeName.value}的店铺`)
            return
          }
        }

        data.schedule = schedule
        data.id = datas.id

        const FunctionName = schedule === 'B' ? submitChange : createSave
        FunctionName(data).then((res: any) => {
          if (res.success === 1) {
            proxy.$toast(schedule === 'B' ? '提交成功' : '保存成功')
            proxy.$SimpleEvents.emit('refreshCustomerChangeItem', data.id)
            if (callback) {
              callback()
              return
            }
            nextTick(() => {
              $router.goBack()
            })
          }
        })
      }
      const onView = () => {
        onSave('A', () => {
          $router.push({
            path: '/dealerShopChange/preview',
            query: {
              id: `${datas.id}`
            }
          })
        })
      }

      const onChangeReceiveManager = (d: any) => {
        const receiveManager = {
          receiveManagerCode: d?.personCode || '',
          receiveManagerName: d?.personName || '',
          receiveManagerTel: d?.personTel || '',
          receiveManagerTypeCode: d?.accountType || '',
          receiveManagerTypeName: d?.accountTypeName || ''
        }
        datas.formData = { ...datas.formData, ...receiveManager }
      }

      const onSearchCustomerManager = () => {
        const officeCode = dealerData.value.officeCode
        const customerCode = datas.detail.customerCode
        if ([undefined, null, ''].includes(officeCode)) {
          proxy.$toast('请先选择办事处')
          return
        }
        proxy.$SimpleEvents.registerEvent('ShopChangeEditSetManager', (data: any) => {
          onChangeReceiveManager(data)
        })
        $router.push({
          path: '/search/customerManager',
          query: {
            name: 'ShopChangeEditSetManager',
            office: officeCode,
            customer: customerCode
          }
        })
      }
      const getDetail = () => {
        const id = `${datas.id}`
        detail(id).then((res) => {
          const d = res.data
          datas.detail = d
          initFormData(d, datas.formData)
        })
      }
      const onEditShop = (data: any) => {
        proxy.$SimpleEvents.registerEvent('ChangeShopUpdateShopInfo', (newData: any) => {
          /* const detail = datas.detail
          detail.shopBusinessDTOS = shopList.value.map((v: any) => {
            if (v.id === newData.id) {
              return { ...v, ...newData }
            }
            return { ...v }
          })
          datas.detail = detail */
          detail(datas.id).then((res) => {
            datas.detail = { ...datas.detail, ...res.data }
          })
        })

        localStorage.setItem('changeShopInfo', JSON.stringify({ ...data, ...{ changeCode: datas.detail.code } }))
        $router.push({
          path: '/dealerShopChange/editShop',
          query: {
            type: datas.detail.type
          }
        })
      }

      getDetail()
      return {
        ...toRefs(datas),
        typeCode,
        typeName,
        dealerData,
        onView,
        onSave,
        onSearchCustomerManager,
        shopList,
        onEditShop
      }
    }
  }
</script>
<style lang="less" scoped>
  .shop-list {
    padding: 0 16px;
    /deep/ .qmp-checkbox__label {
      flex: 1;
    }

    .shop-checkbox {
      display: flex;
      align-items: center;
      overflow: hidden;
      user-select: none;
      .check-status {
        margin-right: 16px;
        width: 24px;
        height: 24px;
        background-repeat: no-repeat;
        background-size: 24px 24px;
        background-image: url(~@/assets/images/checkbox.png);
        &.checked {
          background-image: url(~@/assets/images/checkbox-check.png);
        }
      }
    }
    .shop-item {
      flex: 1;
      padding: 16px 0;
      position: relative;
      &.has-pr {
        padding-right: 56px;
      }
      .title {
        margin-bottom: 2px;
        font: var(--font-main-title-strengthen);
        color: var(--texticon-default-strong);
      }
      .address {
        font: var(--font-main-title-body);
        color: var(--texticon-default-strong);
      }
      .btn-edit {
        position: absolute;
        z-index: 9;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 24px;
        height: 24px;
        background-image: url(~@/assets/images/edit-line.png);
        background-size: 24px 24px;
        background-repeat: no-repeat;
      }
    }
  }
</style>
